const path = require("path");
const fse = require("fs-extra");
const { ErrorModel, SuccessModel } = require("../model/ResModel");

const DIST_FILE_PATH = path.join(__dirname, "..", "..", "uploadFiles");
const MAX_SIZE = 1024 * 1024 * 1024; // 1M

fse.pathExists(DIST_FILE_PATH).then((exist) => {
  if (!exist) {
    fse.ensureDir(DIST_FILE_PATH);
  }
});

async function saveFile({ name, type, size, filePath }) {
  if (size > MAX_SIZE) {
    return ErrorModel.uploadFileSizeFailInfo();
  }
  try {
    const arrTypes = type.split("/");
    let suffix = "jpg";
    if (arrTypes.length > 1) {
      suffix = arrTypes[arrTypes.length - 1];
    }

    const newName = `${Date.now()}.${suffix}`;
    const newPath = path.join(DIST_FILE_PATH, newName);
    await fse.move(filePath, newPath);
    return new SuccessModel({
      url: `/${newName}`,
    });
  } catch (err) {
    console.log(err);
    return new ErrorModel.unNormalFailInfo();
  }
}

module.exports = {
  saveFile,
};
